<template>
  <n-form
    :model="formModel"
    :rules="rules"
    :label-width="80"
    ref="formRef"
    label-placement="top"
  >
    <n-form-item label="登录名" path="username">
      <n-input placeholder="Input" v-model:value="formModel.username" class='item' />
    </n-form-item>
    <n-form-item label="昵称" path="nickname">
      <n-input placeholder="Input" v-model:value="formModel.nickname" class='item' />
    </n-form-item>
    <n-form-item label="联系电话" path="phone">
      <n-input placeholder="Input" v-model:value="formModel.phone" class='item' />
    </n-form-item>
    <n-form-item label="邮箱" path="email">
      <n-input placeholder="Input" v-model:value="formModel.email" class='item' />
    </n-form-item>
    <n-form-item label="性别" path="gender">
      <n-radio-group v-model:value="formModel.gender" name="gender">
        <n-space>
          <n-radio
            v-for='item in genderOption'
            :key='item.dictValue'
            :value='item.dictValue'
            :label='item.dictValue'>{{ item.dictLabel }}</n-radio>
        </n-space>
      </n-radio-group>
    </n-form-item>
    <n-form-item >
      <n-button @click='submit' type='info'>
        更新信息
      </n-button>
    </n-form-item>
  </n-form>
</template>

<script lang="ts" setup>

  import { ref, getCurrentInstance, onMounted, computed, unref } from 'vue'
  import { useStore } from 'vuex'
  import { updateUser } from '@/api/system/user'

  const internalInstance = getCurrentInstance()
  const { $message, $dialog } = internalInstance?.appContext.config.globalProperties
  const store = useStore()
  const genderOption = computed(() => store.getters.genderOption)

  const formModel = ref({
    id: '',
    username: '',
    nickname: '',
    phone: '',
    email: '',
    gender: ''
  })
  const rules = {
    username: {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    nickname: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur'
    },
    phone: {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    }
  }
  const formRef = ref()

  function submit() {
    formRef.value.validate((error: any) => {
      if(!error) {
        $dialog.warning({
          title: '警告',
          content: '确定修改信息吗？',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: () => {
            updateUser(unref(formModel)).then(res => {
              $message.success('修改成功')
            })
          },
          onNegativeClick: null
        })
      }
    })
  }

  onMounted(() => {
    const user = store.getters.user
    formModel.value.id = user.id
    formModel.value.username = user.username
    formModel.value.nickname = user.nickname
    formModel.value.phone = user.phone
    formModel.value.email = user.email
    formModel.value.gender = user.gender
  })

</script>

<style lang='stylus' scoped>
  .item
    width 50%
</style>